#!/usr/bin/env python
# -*- encoding=utf-8 -*-
'''
Created on 2018/8/20

@author: rwx403335
'''

import logging
import logging.config
import os, sys
import codecs, string
reload(sys)
sys.setdefaultencoding('utf8')

if not os.path.isdir("log"):
    os.mkdir("log")
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("copy_jenkins")

BRANCH = os.getenv('GERRIT_BRANCH')
if BRANCH == 'next_net' or BRANCH == 'next_hack' or BRANCH == 'next_docker' or BRANCH == 'next_kernel' or BRANCH == 'next_openeuler':
    BRANCH = 'next'
REPO_DIR = '/usr1/jenkins/EulerOS_' + BRANCH
PROJECT = os.getenv('GERRIT_PROJECT')
project_dir=''


def istextfile(filename, blocksize = 512):
    tmp_obj = open(filename)
    contents = tmp_obj.read(blocksize)
    tmp_obj.close()
    text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
    _null_trans = string.maketrans("", "")
    if '\0' in contents:
        return 0

    if not contents:
        return 1

    t = contents.translate(_null_trans, text_characters)
    if len(t)/len(contents) > 0.30:
        return 0
    return 1

def is_Binary_file(code_base_dir):
    binary_files = []
    if os.path.isfile('files_list'):
        files_obj = open('files_list')
    else:
        logger.error('Get file list falied')
        return 1
    for f in files_obj.readlines():
        f = f.replace('\r','').replace('\n','')
        if f == '/COMMIT_MSG': continue
        if os.path.isfile(code_base_dir + '/' + f) and istextfile(code_base_dir + '/' + f) == 0:
            binary_files.append(f)
    files_obj.close()
    if len(binary_files) > 0:
        logger.error('It is Not Allowded to Upload Binary Files.')
        logger.error('BINARY_FILES: %s' % binary_files)
        logger.error('Please contact [ hexiaowen 00277865 ] to improve your problem')
        return 1
    return 0

if __name__ == "__main__":
    work_dir = os.getcwd()
    if "self_src" in PROJECT:
        project_dir = REPO_DIR + '/' + PROJECT.replace('\n','')
    else:
        project_dir = REPO_DIR + '/' + PROJECT
    os.chdir(work_dir)
    ret = is_Binary_file(project_dir)
    if ret != 0:
        sys.exit(1)
    sys.exit(0)
